import React from 'react';
import {Spin, Card, Button, Table, Row, Col} from 'antd';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import PropTypes from 'prop-types';
import {transportType, partOrderPriceTerms, paymentType, currency} from '../Enum';
import routes from './routes';
import {PERMISSION} from './constants';
import {conventEnumValueToString, formatAmount, formatDateTime} from '../utils';
import {getDetail, abandonData, submitData} from './api';
import {injectIntl} from './intl';
import {hasPermissions} from './utils';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import styles from './style.css';
import {TABLE, DATETIME_FORMAT} from '../constants';
const {Description} = DescriptionList;
const basePath = fetch.basePath || '';
const url = '/#/dcs/parts/partOrderPi/add';
class DetailPanel extends React.PureComponent {
    state = {
        isFetching: false,
        data: {},
        details: [],
        operateLogs: []
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({isFetching: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        data: res.data,
                        details: res.data.details.map(v => Object.assign({}, v, {
                            isDealerUser: this.props.isDealerUser,
                            price: v.price ? v.price : v.estimatedPrice
                        })),
                        operateLogs: res.data.operateLogs
                    });
                else
                    this.setState(({
                        isFetching: false
                    }));
            });
    }
    onCancel = () => {
        this.props.history.push(routes.query.url());
    }
    onClickSubmitBtn = () => {
        this.setState({loading: true});
        const data = {
            rowVersion: this.state.data.rowVersion
        };
        submitData(this.state.data.id, data)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    onClickAbandon = () => {
        this.setState({loading: true});
        const data = {
            rowVersion: this.state.data.rowVersion
        };
        abandonData(this.state.data.id, data)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    render() {
        const {data, operateLogs} = this.state;
        const {formatMessage} = this.props.intl;
        const operations = [];
        let totalNumber = 0;
        let totalKind = 0;
        let totalPrice = 0;
        if(this.state.details) {
            totalKind = this.state.details.length;
            this.state.details.forEach(d => {
                totalNumber += (d.planQuantity);
                totalPrice += (d.planQuantity * d.price);
            });
        }
            
        if(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(data.options, PERMISSION.update))
            operations.push(<Button key="update" href={`#${routes.update.format(this.props.id)}`} size="small">{
                formatMessage({
                    id: 'detailPanel.update',
                    defaultMessage: '编辑'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.assistUpdate) && hasPermissions(data.options, PERMISSION.assistUpdate))
            operations.push(<Button key="assistUpdate" href={`#${routes.assistUpdate.format(this.props.id)}`} size="small">{
                formatMessage({
                    id: 'detailPanel.assistUpdate',
                    defaultMessage: '代编辑'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.submit) && hasPermissions(data.options, PERMISSION.submit))
            operations.push(<WrappedPopconfirm
                key="submit"
                id={this.props.id}
                placement="topLeft"
                onConfirm={this.onClickSubmitBtn}
                title={formatMessage({
                    id: 'detailPanel.validate.submit',
                    defaultMessage: '是否确认提交？'
                })}>
                <Button key="submit" size="small">{
                    formatMessage({
                        id: 'detailPanel.save',
                        defaultMessage: '保存'
                    })
                }</Button>
            </WrappedPopconfirm>);
        if(hasPermissions(this.props.permissions, PERMISSION.assistSubmit) && hasPermissions(data.options, PERMISSION.assistSubmit))
            operations.push(<WrappedPopconfirm
                key="assistSubmit"
                id={this.props.id}
                placement="topLeft"
                onConfirm={this.onClickSubmitBtn}
                title={formatMessage({
                    id: 'detailPanel.validate.assistSubmit',
                    defaultMessage: '是否确认提交？'
                })}>
                <Button key="assistSubmit" size="small">{
                    formatMessage({
                        id: 'detailPanel.assistSubmit',
                        defaultMessage: '代提交'
                    })
                }</Button>
            </WrappedPopconfirm>);
        if(hasPermissions(this.props.permissions, PERMISSION.approve) && hasPermissions(data.options, PERMISSION.approve))
            operations.push(<Button key="approve" href={`#${routes.approve.format(this.props.id)}`} size="small">{
                formatMessage({
                    id: 'detailPanel.approve',
                    defaultMessage: '审核'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(data.options, PERMISSION.abandon))
            operations.push(<WrappedPopconfirm
                key="abandon"
                id={this.props.id}
                placement="topLeft"
                onConfirm={this.onClickAbandon}
                title={formatMessage({
                    id: 'detailPanel.validate.abandon',
                    defaultMessage: '是否确认作废？'
                })}>
                <Button key="abandon" size="small">{
                    formatMessage({
                        id: 'detailPanel.abandon',
                        defaultMessage: '作废'
                    })
                }</Button>
            </WrappedPopconfirm>);
        if(hasPermissions(this.props.permissions, PERMISSION.assistAbandon) && hasPermissions(data.options, PERMISSION.assistAbandon))
            operations.push(<WrappedPopconfirm
                key="assistAbandon"
                id={this.props.id}
                placement="topLeft"
                onConfirm={this.onClickAbandon}
                title={formatMessage({
                    id: 'detailPanel.validate.assistAbandon',
                    defaultMessage: '是否确认作废？'
                })}>
                <Button key="assistAbandon" size="small">{
                    formatMessage({
                        id: 'detailPanel.assistAbandon',
                        defaultMessage: '代作废'
                    })
                }</Button>
            </WrappedPopconfirm>);
        if(hasPermissions(this.props.permissions, PERMISSION.create) && hasPermissions(data.options, PERMISSION.create))
            operations.push(<Button key="create" href={`${basePath}${url}?partSaleOrderId=${data.id}`} target="_blank" size="small">{
                formatMessage({
                    id: 'detailPanel.create',
                    defaultMessage: '生成PI'
                })
            }</Button>);
        const colums = [{
            title: formatMessage({
                id: 'detailPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
            width: 300,
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partName',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'partName',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.unit',
                defaultMessage: '计量单位'
            }),
            dataIndex: 'unit',
            width: 120,
        }, {
            title: formatMessage({
                id: 'detailPanel.column.minPackSize',
                defaultMessage: '最小包装数'
            }),
            dataIndex: 'minPackSize',
            width: 120,
        }, {
            title: formatMessage({
                id: 'detailPanel.column.price',
                defaultMessage: '单价'
            }),
            dataIndex: 'price',
            width: 120,
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.planQuantity',
                defaultMessage: '订购数量'
            }),
            dataIndex: 'planQuantity',
            width: 120,
        }, {
            title: formatMessage({
                id: 'detailPanel.column.approvedQuantity',
                defaultMessage: '审核量'
            }),
            dataIndex: 'approvedQuantity',
            width: 120,
        }];
        
        const columsLogs = [{
            title: formatMessage({
                id: 'detailPanel.column.confirmerName',
                defaultMessage: '操作人'
            }),
            dataIndex: 'confirmerName'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.nowStatus',
                defaultMessage: '操作状态'
            }),
            dataIndex: 'nowStatus'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.approvedContent',
                defaultMessage: '审核意见'
            }),
            dataIndex: 'approvedContent'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.confirmTime',
                defaultMessage: '操作时间'
            }),
            dataIndex: 'confirmTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }];
        return (
            <div>
                <Spin spinning={this.state.isFetching}>
                    <Card>
                        <DescriptionList title={<Row><Col span={6}>{
                            formatMessage({
                                id: 'detailPanel.card.partOtherOrder',
                                defaultMessage: '订单信息'
                            })
                        }</Col>
                        <Col className={`col-align-right ${styles.detail}`} span={18}>{operations}</Col></Row>}>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.code',
                                defaultMessage: '订单编号'
                            })}>{data.code}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.dealer',
                                defaultMessage: '总代'
                            })}>({data.dealerCode}){data.dealerName}</Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.partBackOrderCode',
                                defaultMessage: '缺货单编号'
                            })}>{data.partBackOrderCode}</Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.customerOrderCode',
                                defaultMessage: '客户订单号'
                            })}>{data.customerOrderCode}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.currency',
                                defaultMessage: '币种'
                            })}>{conventEnumValueToString(currency, data.currency)}</Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.country',
                                defaultMessage: '国家'
                            })}>{data.country}</Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.brandName',
                                defaultMessage: '品牌'
                            })}>{data.brandName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.partOrderType',
                                defaultMessage: '订单类型'
                            })}>{data.partOrderTypeName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.paymentType',
                                defaultMessage: '付款方式'
                            })}>{conventEnumValueToString(paymentType, data.paymentType)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.partOrderPriceTerms',
                                defaultMessage: '价格条款'
                            })}>{conventEnumValueToString(partOrderPriceTerms, data.partOrderPriceTerms)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.account',
                                defaultMessage: '到付账号'
                            })}>{data.account}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.carier',
                                defaultMessage: '指定货代'
                            })}>{data.carier}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.receivedCompany',
                                defaultMessage: '收货方'
                            })}>{data.receivedCompany}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.receivedTelephone',
                                defaultMessage: '收货方电话'
                            })}>{data.receivedTelephone}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.receivedPerson',
                                defaultMessage: '收货联系人'
                            })}>{data.receivedPerson}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.receivedPersonPhone',
                                defaultMessage: '收货人联系电话'
                            })}>{data.receivedPersonPhone}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.receivedPort',
                                defaultMessage: '目的港口'
                            })}>{data.receivedPort}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.shipmentPort',
                                defaultMessage: '发运港口'
                            })}>{data.shipmentPort}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.transportType',
                                defaultMessage: '运输方式'
                            })}>{conventEnumValueToString(transportType, data.transportType)}</Description>
                        </DescriptionList>
                        <DescriptionList col="1" className={styles.message}>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.receivedAddress',
                                defaultMessage: '收货地址'
                            })}>{data.receivedAddress}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.approvedContent',
                                defaultMessage: '审核意见'
                            })}>{data.approvedContent}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.remark',
                                defaultMessage: '备注'
                            })}>{data.remark}</Description>
                        </DescriptionList>
                    </Card>
                    <Card>
                        <DescriptionList title={formatMessage({
                            id: 'detailPanel.table.details',
                            defaultMessage: '清单'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={colums}
                                rowKey="partId"
                                dataSource={this.state.details}
                                pagination={false}
                                footer={() => <DescriptionList><Description term={formatMessage({
                                    id: 'detailPanel.operation.totalNumber',
                                    defaultMessage: '订购量汇总'
                                })}>{totalNumber}
                                </Description>
                                <Description term={formatMessage({
                                    id: 'detailPanel.operation.totalKind',
                                    defaultMessage: '品种汇总'
                                })}>{totalKind}
                                </Description>
                                <Description term={formatMessage({
                                    id: 'detailPanel.operation.totalPrice',
                                    defaultMessage: '金额汇总'
                                })}>{formatAmount(totalPrice)}
                                </Description></DescriptionList>}
                                scroll={{
                                    x: 'max-content',
                                    y: 800
                                }}
                                size="small"
                                bordered={true} />
                        </DescriptionList>
                    </Card>
                    <Card>
                        <DescriptionList title={formatMessage({
                            id: 'detailPanel.table.operateLogs',
                            defaultMessage: '操作历史'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={columsLogs}
                                rowKey="id"
                                dataSource={operateLogs}
                                pagination={false}
                                {...TABLE} />
                        </DescriptionList>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Button type="primary" onClick={this.onCancel}>{this.props.intl.formatMessage({
                        id: 'detailPanel.operation.onCancel',
                        defaultMessage: '返回'
                    })}</Button>
                </div>
            </div>
        );
    }
}

DetailPanel.propTypes = {
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
};

import {connect} from 'react-redux';
import {tableSearch} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = (state, props) => ({
    permissions: getPermissions(state),
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
});
const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DetailPanel));
